package com.example.article.service.impl;

import com.example.article.entity.Comment;
import com.example.article.service.CommentService;
import com.example.commonutils.JwtUtils;
import com.example.commonutils.ResultData;
import com.example.servicebase.exceptionhandler.CustomException;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResultData saveCommentById(String articleId, Comment comment, HttpServletRequest request) {
        comment.setGmtCreate(new Date());
        mongoTemplate.save(comment, "comment");
        return ResultData.ok();
    }

    @Override
    public ResultData getComments(String articleId, Integer limit, HttpServletRequest request) {
        //根据课程id去查询评论表
        Query query = new Query(Criteria.where("articleId").is(articleId));
        query.with(Sort.by(
                Sort.Order.desc("gmtCreate")
        ));
        query.limit(limit);
//        wrapper1.eq("course_id",courseId).orderByDesc("gmt_create").last("limit "+limit);
        List<Comment> comments = mongoTemplate.find(query, Comment.class, "comment");
        long size = mongoTemplate.count(query, Comment.class, "comment");
        return ResultData.ok().data("comments", comments).data("size", size);
    }

    @Override
    public ResultData delComment(String commentId, HttpServletRequest request) {
        //从请求中获取token
        String token = JwtUtils.getMemberIdByJwtToken(request);
        String memberId = "";
        if (!StringUtil.isNullOrEmpty(token)) {
            memberId = JwtUtils.getMemberIdByJwtToken(request);
            Query query = new Query(Criteria.where("id").is(commentId));
            Comment comment = mongoTemplate.findOne(query, Comment.class, "comment");
            if (memberId.equals(comment.getUserId())){
                try {
                    mongoTemplate.remove(query, Comment.class, "comment");
                } catch (Exception e) {
                    return ResultData.error().message("删除失败");
                }
            }
        } else {
            throw new CustomException(20001, "请先登录");
        }

        return ResultData.ok();
    }
}
